"""
配置同步管理器
用于同步动态菜单到静态配置文件、路由配置等
"""

import os
import json
import logging
from typing import Dict, List, Any
from django.conf import settings
from django.utils import timezone
from ..models import MenuItem

logger = logging.getLogger(__name__)


class ConfigSyncManager:
    """配置同步管理器"""

    def __init__(self):
        self.frontend_path = os.path.join(settings.BASE_DIR, '..', 'devops-frontend')
        self.config_path = os.path.join(self.frontend_path, 'src', 'config')
        self.router_path = os.path.join(self.frontend_path, 'src', 'router')

    def sync_static_menu_config(self) -> Dict[str, Any]:
        """同步静态菜单配置文件"""
        try:
            # 获取所有菜单数据
            menus = MenuItem.objects.filter(is_enabled=True).order_by('sort_weight', 'order')

            # 构建菜单树
            menu_tree = self._build_menu_tree(menus)

            # 生成配置文件内容
            config_content = self._generate_menu_config_content(menu_tree)

            # 写入配置文件
            config_file_path = os.path.join(self.config_path, 'menus.ts')
            os.makedirs(self.config_path, exist_ok=True)

            with open(config_file_path, 'w', encoding='utf-8') as f:
                f.write(config_content)

            logger.info(f"静态菜单配置已同步到: {config_file_path}")

            return {
                'success': True,
                'file_path': config_file_path,
                'menu_count': len(menu_tree)
            }

        except Exception as e:
            logger.error(f"同步静态菜单配置失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }

    def sync_route_config(self) -> Dict[str, Any]:
        """同步路由配置"""
        try:
            # 获取所有菜单数据
            menus = MenuItem.objects.filter(is_enabled=True).order_by('sort_weight', 'order')

            # 生成路由配置
            routes = self._generate_route_config(menus)

            # 读取现有路由文件
            router_file_path = os.path.join(self.router_path, 'index.ts')

            if os.path.exists(router_file_path):
                with open(router_file_path, 'r', encoding='utf-8') as f:
                    router_content = f.read()

                # 更新动态路由部分
                updated_content = self._update_router_content(router_content, routes)

                # 写回文件
                with open(router_file_path, 'w', encoding='utf-8') as f:
                    f.write(updated_content)

                logger.info(f"路由配置已同步到: {router_file_path}")

                return {
                    'success': True,
                    'file_path': router_file_path,
                    'route_count': len(routes)
                }
            else:
                return {
                    'success': False,
                    'error': f'路由文件不存在: {router_file_path}'
                }

        except Exception as e:
            logger.error(f"同步路由配置失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }

    def sync_permission_config(self) -> Dict[str, Any]:
        """同步权限配置"""
        try:
            # 获取所有菜单的权限代码
            menus = MenuItem.objects.filter(is_enabled=True).exclude(permission_code__isnull=True).exclude(permission_code='')

            # 生成权限映射
            permission_mapping = {}
            path_mapping = {}

            for menu in menus:
                if menu.permission_code:
                    permission_mapping[menu.permission_code] = f'view_{menu.component_name or menu.name.lower()}'
                    path_mapping[menu.path] = menu.permission_code

            # 更新后端权限配置
            self._update_backend_permissions(permission_mapping, path_mapping)

            logger.info("权限配置已同步")

            return {
                'success': True,
                'permission_count': len(permission_mapping),
                'path_count': len(path_mapping)
            }

        except Exception as e:
            logger.error(f"同步权限配置失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }

    def full_sync(self) -> Dict[str, Dict[str, Any]]:
        """完整同步所有配置"""
        results = {}

        # 同步静态菜单配置
        results['static_config'] = self.sync_static_menu_config()

        # 同步路由配置
        results['route_config'] = self.sync_route_config()

        # 同步权限配置
        results['permission_config'] = self.sync_permission_config()

        return results

    def _build_menu_tree(self, menus) -> List[Dict[str, Any]]:
        """构建菜单树结构"""
        menu_dict = {}
        root_menus = []

        # 先创建所有菜单项的字典
        for menu in menus:
            menu_dict[menu.id] = {
                'id': menu.id,
                'name': menu.name,
                'path': menu.path,
                'icon': menu.icon,
                'order': menu.sort_weight or menu.order,
                'permission_code': menu.permission_code,
                'parent_id': menu.parent_id,
                'children': []
            }

        # 构建父子关系
        for menu in menus:
            menu_item = menu_dict[menu.id]
            if menu.parent_id and menu.parent_id in menu_dict:
                menu_dict[menu.parent_id]['children'].append(menu_item)
            else:
                root_menus.append(menu_item)

        return root_menus

    def _generate_menu_config_content(self, menu_tree: List[Dict[str, Any]]) -> str:
        """生成菜单配置文件内容"""
        def format_menu_item(item: Dict[str, Any], indent: int = 0) -> str:
            spaces = '  ' * indent
            children_str = ''

            if item['children']:
                children_content = ',\n'.join([
                    format_menu_item(child, indent + 2)
                    for child in item['children']
                ])
                children_str = f",\n{spaces}  children: [\n{children_content}\n{spaces}  ]"

            return f"""{spaces}{{
{spaces}  id: '{item['id']}',
{spaces}  name: '{item['name']}',
{spaces}  path: '{item['path']}',
{spaces}  icon: '{item['icon']}',
{spaces}  order: {item['order']},
{spaces}  permission_code: '{item['permission_code'] or ''}'{',' if item['parent_id'] else ''}
{spaces}  parent_id: {f"'{item['parent_id']}'" if item['parent_id'] else 'null'}{children_str}
{spaces}}}"""

        menu_items = ',\n'.join([format_menu_item(item, 1) for item in menu_tree])

        return f"""// 自动生成的菜单配置文件
// 生成时间: {timezone.now().isoformat()}

export interface MenuItem {{
  id: string | number
  name: string
  path: string
  icon: string
  order: number
  permission_code?: string
  parent_id?: string | number | null
  children?: MenuItem[]
}}

export const STATIC_MENUS: MenuItem[] = [
{menu_items}
]

// 权限代码映射
export const PERMISSION_CODES = {{
{self._generate_permission_codes(menu_tree)}
}}

export default STATIC_MENUS
"""

    def _generate_permission_codes(self, menu_tree: List[Dict[str, Any]]) -> str:
        """生成权限代码映射"""
        codes = []

        def extract_permissions(items: List[Dict[str, Any]]):
            for item in items:
                if item.get('permission_code'):
                    codes.append(f"  '{item['permission_code']}': '{item['name']}'")
                if item.get('children'):
                    extract_permissions(item['children'])

        extract_permissions(menu_tree)
        return ',\n'.join(codes)

    def _generate_route_config(self, menus) -> List[Dict[str, Any]]:
        """生成路由配置"""
        routes = []

        for menu in menus:
            if menu.is_generated and menu.component_name:
                route = {
                    'path': menu.path,
                    'name': menu.component_name,
                    'component': f"() => import('@/views/generated/{menu.component_name}.vue')",
                    'meta': {
                        'title': menu.name,
                        'icon': menu.icon
                    }
                }
                routes.append(route)

        return routes

    def _update_router_content(self, content: str, routes: List[Dict[str, Any]]) -> str:
        """更新路由文件内容"""
        # 这里应该实现更复杂的路由更新逻辑
        # 暂时返回原内容，实际应该解析并更新动态路由部分
        return content

    def _update_backend_permissions(self, permission_mapping: Dict[str, str], path_mapping: Dict[str, str]):
        """更新后端权限配置"""
        # 这里应该更新views.py中的权限映射
        # 暂时只记录日志
        logger.info(f"需要更新权限映射: {len(permission_mapping)} 个权限")
        logger.info(f"需要更新路径映射: {len(path_mapping)} 个路径")
